<!DOCTYPE html>
<title>Test that media keeps playing when the source element is replaced.</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<audio></audio>
<script>
async_test(function(t) {
    // TODO(srirama.m): Improve the test for better understanding
    var timeupdateEventCount = 0;
    var sourceReplaced = false;

    var audio = document.querySelector("audio");
    var source = document.createElement("source");
    source.src = "content/silence.oga";
    audio.appendChild(source);

    audio.onerror = t.unreached_func();

    audio.ontimeupdate = t.step_func(function() {
        ++timeupdateEventCount;

        if (timeupdateEventCount == 1) {
            // If the media play has started it should continue even if
            // source was replaced. Wait for two timeupdate events to
            // make sure the same source keeps playing.
            if (sourceReplaced)
                assert_greater_than(audio.currentTime, 0);
        } else if (timeupdateEventCount == 2) {
            // We wait 2 timeupdate events so we are sure the media engine
            // is playing the media, and make sure time is advancing.
            assert_greater_than(audio.currentTime, 0);
            if (!sourceReplaced) {
                // Replacing the media's source element.
                sourceReplaced = true;
                timeupdateEventCount = 0;

                audio.removeChild(source);
                var newSource = document.createElement("source");
                newSource.src = "content/test.oga";
                audio.appendChild(newSource);
            } else {
                t.done();
            }
        }
    });

    assert_equals(audio.currentTime, 0);
    audio.play();
});
</script>